package EventDispatchers
{
	import Events.XMLEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;

	
	/**
	 * This class loads XML data in one shot, calls the callback function,
	 * then destroys itself
	 * 
	 */	
	public class XMLLoader extends EventDispatcher
	{
		private var xmlLoader:URLLoader;
				
		public function XMLLoader()
		{
			xmlLoader = new URLLoader();			
		}
		
		public function load($url:String):void {
			var request:URLRequest;
			
			//--Add listeners
			xmlLoader.addEventListener(Event.COMPLETE, xmlComplete);
			xmlLoader.addEventListener(IOErrorEvent.IO_ERROR, ioError);
			xmlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			
			//--Load xml request
			request = new URLRequest($url);
			var header:URLRequestHeader = new URLRequestHeader("pragma", "no-cache");
			request.requestHeaders.push(header);
			xmlLoader.load(request);
		}
		
		private function xmlComplete($event:Event):void
		{
			//--Get data
			var data:XML = new XML($event.target.data);	
			dispatchEvent(new Events.XMLEvent(XMLEvent.XMLLOADED, data));
			//--Complete task
			complete();
		}
		
		private function ioError($event:IOErrorEvent):void {
			trace( "XMLLoader failed because of I/O error: " + $event.text);
			
			complete();
		}
		
		private function securityError($event:SecurityErrorEvent):void {
			trace( "XMLLoader failed because of security error: " + $event.text);
			
			complete();
		}
		
		private function complete():void
		{
			//--Remove listeners
			xmlLoader.removeEventListener(Event.COMPLETE, xmlComplete);
			xmlLoader.removeEventListener(IOErrorEvent.IO_ERROR, ioError);
			xmlLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
			
			//--Destroy
			destroy();
		}
		
		private function destroy():void {
			xmlLoader = null;
		}

	};
};